/**
 * Created by wenguangjia on 2017/9/5.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('deployDashController', deployDashController);
    deployDashController.$inject = ['$scope', '$sce', 'ACTIVE', 'kibanaPartition', 'deployDashService'];

    function deployDashController($scope, $sce, active, kibanaPartition, deployDashService) {

        var onlineSortEcharts = echarts.init(angular.element('#onlineSortEcharts')[0]);
        var onlineTrendEcharts = echarts.init(angular.element('#onlineTrendEcharts')[0]);


        $scope.startTime = getToday00Clock().Format("yyyy-MM-ddThh:mm:ss.S");
        $scope.endTime = getToday11Clock().Format("yyyy-MM-ddThh:mm:ss.S");
        $scope.interval = 1800000;
        $scope.quick = true;
        $scope.timeType = "1d";
        var title = [];
        var arr = [];
        var partitionArr = [];
        var currentTime = new Date();
        var yCount = [];
        queryOnlineSort();
        queryOnlineTrend();

        function queryOnlineSort() {
            deployDashService.queryOnlineSort($scope.startTime, $scope.endTime, active).then(
                function (resp) {
                    onlineSortAnalysis(resp);
                }, function (error) {
                    console.log(error);
                    notify('error', '失败', error.message);
                });
        }

        function onlineSortAnalysis(data) {
            var xService = [];
            var partitionAndCount = [];
            partitionArr = [];
            arr = [];
            if (data.length != 0) {
                angular.forEach(data, function (item) {
                    xService.push(item.service);
                    partitionAndCount.push(item.hashMap);

                });
                angular.forEach(partitionAndCount, function (item) {
                    for (var key in item) {
                        if (partitionArr.indexOf(key) == -1) {
                            partitionArr.push(key);
                        }
                    }
                });

                angular.forEach(partitionArr, function (partition) {
                    angular.forEach(partitionAndCount, function (item) {
                        if (item[partition] == undefined) {
                            arr.push("0")
                        } else {
                            arr.push(item[partition])
                        }
                    });
                });

                console.log(arr.length);
                var onlineSortOption = {
                    //color: ['#BC52BC'],
                    title: {
                        text: kibanaPartition + "后台上线排行",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    },
                    legend: {
                        orient: 'horizontal',
                        top: '3%',
                        right: '0%',
                        data: partitionArr
                    },
                    tooltip: {
                        trigger: 'axis',
                        position: function(point, params, dom, rect, size){
                            //其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
                            var x = point[0];//
                            var y = point[1];
                            var boxWidth = size.contentSize[0];
                            var boxHeight = size.contentSize[1];
                            var posX = 0;//x坐标位置
                            var posY = 0;//y坐标位置
                            if(x<boxWidth){//左边放不开
                                posX = 5;
                            }else{//左边放的下
                                posX = x-boxWidth;
                            }
                            if(y<boxHeight){//上边放不开
                                posY = 5;
                            }else{//上边放得下
                                posY = y-boxHeight;
                            }
                            return [posX,posY];
                        },
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        },

                        formatter: function (params) {
                            var res = "";
                            angular.forEach(params, function (item) {
                                res += "<span >上线次数:" + "&emsp;" + item.value + '</span>' + "&emsp;" + '|' + "&emsp;"
                                    + "<span>partition:" + "&emsp;" + item.seriesName + "</span>" + "&emsp;" + '|' + "&emsp;"
                                    + "<span>应用名:" + "&emsp;" + item.name + "</span>" + '<br>' + '<hr>'
                            });
                            return res;
                        }
                    },
                    toolbox: {
                        show: true,
                        orient: 'horizontal',
                        x: 'right',
                        y: 'top',
                        showTitle: true,
                        feature: {
                            magicType: {
                                show: true,
                                title: {
                                    stack: '堆积',
                                    tiled: '平铺'
                                },
                                type: ['stack', 'tiled']
                            }
                        }
                    },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '8%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: xService,
                            name: '应用名',
                            nameLocation: "center",
                            nameGap: 100,
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: {
                                rotate: 45
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            //name:"",
                            nameRotate: "90",
                            nameLocation: "center",
                            nameGap: 40,
                            splitLine: { //网格线
                                show: true
                            },
                            textStyle: {
                                fontSize: 14,
                                fontWeight: "bold",
                            }
                        }
                    ],
                    series: onlineSortSeries(xService.length, partitionArr.length)
                };
                onlineSortEcharts.setOption(onlineSortOption, true);
            } else {
                var onlineSortOption = {
                    title: {
                        text: kibanaPartition + "后台上线排行",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    }

                };
                onlineSortEcharts.setOption(onlineSortOption, true);
            }
            ;

        }

        function queryOnlineTrend() {
            deployDashService.queryOnlineTrend($scope.startTime, $scope.endTime, $scope.interval, active).then(
                function (resp) {
                    onlineTrendAnalysis(resp);
                }, function (error) {
                    console.log(error);
                    notify('error', '失败', error.message);
                });
        }

        function onlineTrendAnalysis(data) {
            var xTime = [];
            var timeAndCountArr = [];
            yCount = [];
            title = [];
            arr = [];
            var timekey1=[];
            var timeValue=[];

            if (data.length != 0) {
                angular.forEach(data, function (item) {
                    timeAndCountArr.push(item.hashMap);

                    title.push(item.service);

                });

                angular.forEach(timeAndCountArr, function (item) {
                    for (var key in item) {
                        if ($scope.timeType == '1w'||$scope.timeType == '1m'){
                           key=key.split("+")[0];
                        }else {
                            key=timestampToTime(key);
                        }
                        if (xTime.indexOf(key) == -1) {
                            xTime.push(key);
                        }
                    }
                });
                xTime = xTime.sort();

                angular.forEach(timeAndCountArr, function (item) {
                    timekey1 = [];
                    timeValue = [];
                    for (var timeKey in item) {
                        timekey1.push(timestampToTime(timeKey));
                        timeValue.push(item[timeKey]);
                    }


                    angular.forEach(xTime,function (time) {
                        if ($scope.timeType == '1w'||$scope.timeType == '1m'){
                            time= timestampToTime(time)
                        }
                        if(timekey1.includes(time)){
                          for (var i = 0 ; i <timekey1.length;i++){
                              if (timekey1[i]==time){
                                  yCount.push(timeValue[i]);
                              }
                          }
                      }else {
                          yCount.push("0");
                      }

                    })

                })




                var onlineTrendOption = {
                    title: {
                        text: kibanaPartition + "后台上线趋势",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    },
                    legend: {
                        orient: 'horizontal',
                        top: '3%',
                        right: '0%',
                        data: title
                    },
                    tooltip: {
                        //trigger: 'axis',
                        trigger: 'axis',
                        position: function(point, params, dom) {
                            return [point[0], '10%'];
                        },
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'line'        // 默认为直线，可选为：'line' | 'shadow'
                        },

                        formatter: function (params) {
                            var res = "";
                            angular.forEach(params, function (item) {
                                res += "<span >上线次数:" + "&emsp;" + item.value + '</span>' + "&emsp;" + '|' + "&emsp;"
                                    + "<span>partition:" + "&emsp;" + item.seriesName + "</span>" + "&emsp;" + '|' + "&emsp;"
                                    + "<span>时间:" + "&emsp;" + item.name + "</span>" + '<br>' + '<hr>'
                            });
                            return res;
                        }
                    },
                    toolbox: {
                        show: true,
                        orient: 'vertical'
                    },
                    grid: {
                        top:'10%',
                        left: '4%',
                        right: '4%',
                        bottom: '8%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: xTime,
                            nameTextStyle:{
                              padding:5
                            },
                            name: 'Time',
                            nameLocation: "center",
                            nameGap: 150,
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: {
                                rotate: 60
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            //name:"",
                            nameRotate: "90",
                            nameLocation: "center",
                            nameGap: 40,
                            splitLine: { //网格线
                                show: true
                            },
                            textStyle: {
                                fontSize: 14,
                                fontWeight: "bold",
                            }
                        }
                    ],
                    series: onlineTrendSeries(xTime.length, title.length)
                };
                onlineTrendEcharts.setOption(onlineTrendOption, true);
            } else {
                var onlineTrendOption = {
                    title: {
                        text: kibanaPartition + "后台上线排行",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    }

                };
                onlineTrendEcharts.setOption(onlineTrendOption, true);
            }
            ;

        }

        function onlineSortSeries(serviceLength, partitionLength) {
            var lgend_data = [];
            for (var i = 0; i < partitionLength; i++) {
                var item = {
                    name: partitionArr[i],
                    type: 'bar',
                    stack:partitionArr[i],
                    data: arr.splice(0, serviceLength)
                }

                lgend_data.push(item);
            }
            ;
            return lgend_data;
        }

        function onlineTrendSeries(xLength, partitionLength) {
            var lgend_data = [];
            for (var i = 0; i < partitionLength; i++) {
                var item = {
                    name: title[i],
                    type: 'line',
                    data: yCount.splice(0, xLength)
                }

                lgend_data.push(item);
            }
            ;
            return lgend_data;
        }









        $scope.select = function () {
            if ($scope.timeType == '1d') {
                $scope.startTime = getToday00Clock().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getToday11Clock().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval = 1800000;
                queryOnlineSort();
                queryOnlineTrend();

            } else if ($scope.timeType == '1h') {
                currentTime.setHours(currentTime.getHours() - 1);
                $scope.startTime = (currentTime.Format("yyyy-MM-ddThh:mm:ss.S"));
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval = 60000;

                queryOnlineSort();
                queryOnlineTrend();
            } else if ($scope.timeType == '4h') {
                currentTime.setHours(currentTime.getHours() - 4);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval = 300000;
                queryOnlineSort();
                queryOnlineTrend();

            } else if ($scope.timeType == '12h') {
                currentTime.setHours(currentTime.getHours() - 12);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval = 600000;
                queryOnlineSort();
                queryOnlineTrend();

            } else if ($scope.timeType == '1m') {
                $scope.startTime = getMonthStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getMonthEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval =43200000;
                queryOnlineSort();
                queryOnlineTrend();
            } else if ($scope.timeType == '1w') {
                $scope.startTime = getWeekStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getWeekEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.interval =10800000;
                queryOnlineSort();
                queryOnlineTrend();

            }

        }


        window.onresize = function(){
            onlineTrendEcharts.resize();
            onlineSortEcharts.resize();
        }

    }
































})();
